package org.edu.modules.oa.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.ApiOperation;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.modules.oa.config.HttpURLConnectionUtil;
import org.edu.modules.oa.entity.VeXoaUserPriv;
import org.edu.modules.oa.entity.bo.BasicResponseBO;
import org.edu.modules.oa.mapper.VeXoaCommonUserPrivMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Auther 李少君
 * @Date 2021-07-31 14:22
 */
@RestController
@RequestMapping("oa/userPriv")
@Slf4j
public class VeXoaCommonUserPrivController {

    @Value("${common.host}")
    private String dirHost ;

    @Autowired
    ObjectMapper mapper;

    @Resource
    private VeXoaCommonUserPrivMapper veXoaCommonUserPrivMapper;



    private String interfaceUserId = "interfaceUserId=09d5e1e7f9b049008eee645c783a1d67";

    @AutoLog(value = "同步角色数据")
    @ApiOperation(value = "获取并同步用户角色表", notes = "获取并同步用户角色表")
    @PostMapping(value = "/synchronousRole")
    public Result<?> userPriv(){
        String url = "common/veCommon/querySysRoleList?"+interfaceUserId;
        BasicResponseBO<List> b = getUrl(url,List.class) ;
        List<VeXoaUserPriv> result = JSONObject.parseArray(JSON.toJSONString(b.getResult()), VeXoaUserPriv.class);
        List<VeXoaUserPriv> list = veXoaCommonUserPrivMapper.getUserMessage(); //获取所有角色信息
        for (int i = 0; i < result.size(); i++) {
            List<VeXoaUserPriv> p = veXoaCommonUserPrivMapper.getRoleById(result.get(i).getId());
            if(p.size()==0){
                veXoaCommonUserPrivMapper.addUserPriv(result.get(i).getId(),result.get(i).getText());
            }else{
                veXoaCommonUserPrivMapper.updateUserPriv(result.get(i).getId(),result.get(i).getText());
            }
        }

        return Result.OK();
    }





    /**
     * 调用公告数据接口
     */
    private <T> BasicResponseBO<T> getUrl(String url, Class<T> clazz) {
        try {
            url = dirHost+url ;
            String result = HttpURLConnectionUtil.doGet(url) ;
            BasicResponseBO<T> re = mapper.readValue(result, new TypeReference<BasicResponseBO<T>>() {});
            T body = mapper.readValue(mapper.writeValueAsString(re.getResult()), clazz);
            re.setResult(body);
            return re;
        } catch (Exception e) {
            return new BasicResponseBO<T>().setSuccess(false).setMessage("操作失败");
        }
    }
}
